package com.lkd.http.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.lkd.common.UserConstants;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.entity.TaskTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.http.view.TokenObject;
import com.lkd.http.vo.*;
import com.lkd.service.*;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/task")
public class TaskController extends BaseController {
    @Autowired
    private TaskService taskService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private TaskTypeService taskTypeService;

    @Autowired
    private UserService userService;

    @Autowired
    private MqttProducer mqttProducer;


    /**
     * 搜索工单
     *
     * @param pageIndex
     * @param pageSize
     * @param innerCode 设备编号
     * @param userId    工单所属人Id
     * @param taskCode  工单编号
     * @param status    工单状态
     * @param isRepair  是否是维修工单
     * @return
     */
    @GetMapping("/search")
    public Pager<TaskEntity> search(
            @RequestParam(value = "pageIndex", required = false, defaultValue = "1") Long pageIndex,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Long pageSize,
            @RequestParam(value = "innerCode", required = false, defaultValue = "") String innerCode,
            @RequestParam(value = "userId", required = false, defaultValue = "") Integer userId,
            @RequestParam(value = "taskCode", required = false, defaultValue = "") String taskCode,
            @RequestParam(value = "status", required = false, defaultValue = "") Integer status,
            @RequestParam(value = "isRepair", required = false, defaultValue = "") Boolean isRepair,
            @RequestParam(value = "start", required = false, defaultValue = "") String start,
            @RequestParam(value = "end", required = false, defaultValue = "") String end) {
        return taskService.search(pageIndex, pageSize, innerCode, userId, taskCode, status, isRepair, start, end);
    }


    /**
     * 根据taskId查询
     *
     * @param taskId
     * @return 实体
     */
    @GetMapping("/taskInfo/{taskId}")
    public TaskEntity findById(@PathVariable Long taskId) {
        return taskService.getById(taskId);
    }


    @GetMapping("/allTaskStatus")
    public List<TaskStatusTypeEntity> getAllStatus() {
        return taskService.getAllStatus();
    }

    /**
     * 获取工单类型
     *
     * @return
     */
    @GetMapping("/typeList")
    public List<TaskTypeEntity> getProductionTypeList() {
        return taskTypeService.list();
    }

    /**
     * 获取工单详情
     *
     * @param taskId
     * @return
     */
    @GetMapping("/details/{taskId}")
    public List<TaskDetailsEntity> getDetail(@PathVariable long taskId) {
        return taskDetailsService.getByTaskId(taskId);
    }


    @PostMapping("/create")
    public boolean create(@RequestBody TaskViewModel taskViewModel) {
        Integer userId = getUserId();
        taskViewModel.setAssignorId(userId);
        //参数校验 省略...
        return taskService.create(taskViewModel);
    }

    @GetMapping("/accept/{taskId}")
    public boolean accept(@PathVariable("taskId") Long taskId) {
        Integer userId = getUserId(); //登录用户id
        TaskEntity task = taskService.getById(taskId); //查询工单
        if (task == null) {
            throw new LogicException("工单不存在!");
        }
        Integer userId1 = task.getUserId();  //工单处理人
        if (!Objects.equals(userId, userId1)) {  //登录用户和工单处理人id不一致
            throw new LogicException("工单处理无权限!");
        }

        //接收工单
        return taskService.accept(task);
    }

    @PostMapping("/cancel/{taskId}")
    public boolean cancel(@PathVariable("taskId") Long taskId, @RequestBody CancelTaskViewModel model) {
        Integer userId = getUserId(); //登录用户id
        TaskEntity task = taskService.getById(taskId); //查询工单
        if (task == null) {
            throw new LogicException("工单不存在!");
        }
        UserVO user = userService.getUser(userId);
        if (!Objects.equals(user.getRoleCode(), UserConstants.ROLE_CODE_ADMIN)) {
            Integer userId1 = task.getUserId();  //工单处理人
            if (!Objects.equals(userId, userId1)) {  //登录用户和工单处理人id不一致
                throw new LogicException("工单处理无权限!");
            }
        }

        //拒绝工单
        task.setDesc(model.getDesc());
        return taskService.cancel(task);
    }

    //完成
    @GetMapping("/complete/{taskId}")
    public boolean complete(@PathVariable("taskId") Long taskId) {
        Integer userId = getUserId(); //登录用户id
        TaskEntity task = taskService.getById(taskId); //查询工单
        if (task == null) {
            throw new LogicException("工单不存在!");
        }
        Integer userId1 = task.getUserId();  //工单处理人
        if (!Objects.equals(userId, userId1)) {  //登录用户和工单处理人id不一致
            throw new LogicException("工单处理无权限!");
        }

        //接收工单
        return taskService.complete(task);
    }

    @GetMapping("/test")
    public void test() {
        TokenObject tokenObject = new TokenObject();
        tokenObject.setMobile("18012345678");
        try {
            mqttProducer.send("test", 1, tokenObject);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/taskReportInfo/{start}/{end}")
    public List<TaskReportInfoVO> taskReportInfo(@PathVariable("start")
                               @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                                       LocalDateTime start
            , @PathVariable("end") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end) {

        List<TaskReportInfoVO> result = taskService.taskReportInfo(start,end);
        return result;
    }

    @GetMapping("/userWorkTop10/{start}/{end}/{isRepair}/{regionId}")
    public List<UserWorkTopVO> userWorkTop10(
            @PathVariable("start") String start,
            @PathVariable("end") String end,
            @PathVariable("isRepair") boolean isRepair,
            @PathVariable("regionId") long regionId
    ) {
        //转换类型
        LocalDate startDate = LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE);
        LocalDate endDate = LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE);
        return taskService.userWorkTop10(startDate,endDate,isRepair,regionId);
    }

    @GetMapping("/collectReport/{start}/{end}")
    public List<CollectTaskVo> collectReport(@PathVariable("start") String start,
                                             @PathVariable("end") String end){
        LocalDate startDate = LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE);
        LocalDate endDate = LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE);
        List<CollectTaskVo> result = taskService.collectReport(startDate,endDate);
        return result;
    }

}